<template>
  <Spin :spinning="loading" tip="Loading...">
  <div>
    <!-- 索赔扣款信息查询-详情页面 -->
    <BreakSpace label="经销商规则新增" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel" :list="formList" :cols="2" :formType="'add'" labelWidth="120" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <BaseDialog :visible.sync="visibleAdd" :title="'选择经销商'" destroyOnClose width="850px" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <DealerList @close="closeAdd" @save="saveAdd"></DealerList>
    </BaseDialog>
    <BaseDialog :visible.sync="visible" :title="'车型新增'" destroyOnClose
                :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <vehicle @close="chexingclose" @save="chexingsave"></vehicle>
    </BaseDialog>
    <BaseDialog :visible.sync="zhusunjian" :title="'主损件选择'" destroyOnClose
                :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <Selectzhusunjian @close="zhusunjianClose" @save="zhusunjianSave"></Selectzhusunjian>
    </BaseDialog>
    <BaseDialog :visible.sync="visibleVin" :title="'VIN新增'" destroyOnClose
                :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <VinVehicle @close="vinclose" @save="vinsave"></VinVehicle>
    </BaseDialog>
    <BreakSpace label="经销商列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :dataSource="dataList"
      :datakey="'items'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      selectionType="single"
      :isSelectColumn=false
      height="auto"
    >


      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" icon="el-icon-plus" :click="add.bind()">添加</multiuse-button>
      </template>
    </FilterTable>
    <BreakSpace label="主损件列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table2"
      :columns="columnsPart"
      :params="fetchParams"
      :datakey="'items'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      height="auto"
      selectionType="single"
      :isSelectColumn=false
      :isPagination = false
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="selectpartCode()">添加</multiuse-button>
      </template>
    </FilterTable>
    <div style="padding-top: 3rem;"></div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <multiuse-button type="primary" :click="saveDialog.bind()">保 存</multiuse-button>
      <multiuse-button @click="closeDialog">关 闭</multiuse-button>
    </div>
  </div>
  </Spin>
</template>
<script>
// import res from '@/mock/tableData';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import { newSave,quryRules,editSave } from '@/api/claim/factory/QualityInformationManagement_OEM/QualityInformationRules/index';
import { isFormEmpty } from '@/utils/index';
import moment from "moment";
import vehicle from '@/pages/claimDemage/tools/ModelVehicle.vue';
import Selectzhusunjian from '@/pages/claimDemage/tools/vehicle.vue';
import VinVehicle from '@/pages/claimDemage/tools/VinVehicle.vue';
import { dictionary } from '@/utils/dictMixin';
export default {
  props: ['rowData'],
  mixins: [dictionary],
   components: {
     DealerList,
     vehicle,
     Selectzhusunjian,
     VinVehicle
  },
  data() {
    return {
      loading: false,
      dataList: [],
      dataList1: [],
      huanxiajiandataList: [],
      fujiaxiangmudataList: [],
      visible: false,
      visibleDrawer: false,
      selectDelearFlag: false,
      collapse: false,
      infoId: null,
      // topFilterInit: this.topFilterInitFun(),
      flterValue: {}, //参数
      columns: this.creatHeader(),
      columnsPart: this.creatHeaderPart(),
      // fetchApi: getUser,
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      formList: this.createFormList(),
      saveData: null,
      visibleAdd: false,
      zhusunjian:false,
      visibleVin:false
    };
  },
  async mounted() {
    this.loading = true;
    if (this.rowData) {
      this.type = 2;
      this.ruleId = this.rowData.ruleId;
      await this.getViewDetail(this.ruleId);
      console.log(this.rowData, '带进来的信息');
    }
    this.loading = false;
  },
  methods: {
    formChangeHandle(val) {
      console.log(val);
      this.saveData = val;
    },//经销商选择页面
    SelectDelear() {
      this.selectDelearFlag = true;
    }, //关闭
    async getViewDetail(ruleId) {
      let res = await quryRules({ id: ruleId });
      let data = res.data;
      this.createdBy = data.createdBy;
      this.isDeleted = data.isDeleted;
      //为2个form赋值
      for (let i in data) {
        this.formList.map(y => {
          if (i == y.fieldName) {
            y.initialValue = data[i];
          }if ('beginDate|endDate' == y.fieldName) {
            y.initialValue =[data.beginDate,data.endDate];
          }
          if ('beginEffectDate|endEffectDate' == y.fieldName) {
            y.initialValue =[data.beginEffectDate,data.endEffectDate];
          }
          if ('proBeginDate|proEndDate' == y.fieldName) {
            y.initialValue =[data.proBeginDate,data.proEndDate];
          }
          if ('saleBeginTime|saleEndTime' == y.fieldName) {
            y.initialValue =[Number(data.saleBeginTime),Number(data.saleEndTime)];
          }
        });
      }
      let records1 = data.list;
      if (isFormEmpty(records1)) {
        records1 = [];
      }
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(records1);

      let records2 = data.partList;
      if (isFormEmpty(records1)) {
        records2 = [];
      }
      this.$refs.table2.$refs.pageTable.EXECUTE_INSERT(records2);
    },
    saveAdd(val) {
      let data = {};
      let falg = true ;
      data.dealerCode = val[val.length - 1].dealerCode;
      data.dealerName = val[val.length - 1].dealerName;
      console.log(data.dealerCode);
      this.$refs.table.$refs.pageTable.list.map(x => {
        if(data.dealerCode == x.dealerCode){
          console.log(data.dealerCode);
          console.log(x.dealerCode);
          falg = false;
          this.$notify.error({ title: '提示信息', message: '经销商选择重复' });
        }
      });
      if(falg){
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(data);
      }
      this.visibleAdd = false;
    },
    closeAdd() {
      this.visibleAdd = false;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = val;
      console.log(val);
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    //保存
    async saveDialog() {
      if(this.type==2){
        this.$refs.formPanel.SUBMIT_FORM();
        if (this.saveData) {
          // this.saveData.ruleType = 58021003;
          this.saveData.ruleId = this.rowData.ruleId;
          this.saveData.isDeleted = this.rowData.isDeleted;
          this.saveData.createdAt = this.rowData.createdAt;
          this.saveData.createdBy = this.createdBy;
          this.saveData.appId = this.rowData.appId;
          if(this.saveData.beginDate){
            this.saveData.beginDate = moment(this.saveData.beginDate).format('YYYY-MM-DD HH:mm:ss');
          }
          if(this.saveData.endDate){
            this.saveData.endDate = moment(this.saveData.endDate).format('YYYY-MM-DD HH:mm:ss');
          }
          let arr3 = [];
          this.$refs.table.$refs.pageTable.list.map(x => {
            arr3.push(x);
          });
          this.saveData.list = arr3;

          let arr4 = [];
          this.$refs.table2.$refs.pageTable.list.map(x => {
            arr4.push(x);
          });
          this.saveData.partList = arr4;
          if(this.saveData.beginEffectDate){
            this.saveData.beginEffectDate = moment(this.saveData.beginEffectDate).format('YYYY-MM-DD HH:mm:ss');
          }
          if(this.saveData.endEffectDate){
            this.saveData.endEffectDate = moment(this.saveData.endEffectDate).format('YYYY-MM-DD HH:mm:ss');
          }
          if(this.saveData.proDate){
            this.saveData.proDate = moment(this.saveData.proDate).format('YYYY-MM-DD HH:mm:ss');
          }
          if( this.saveData.proBeginDate){
            this.saveData.proBeginDate = moment(this.saveData.proBeginDate).format('YYYY-MM-DD HH:mm:ss');
          }
          if( this.saveData.proEndDate){
            this.saveData.proEndDate = moment(this.saveData.proEndDate).format('YYYY-MM-DD HH:mm:ss');
          }
          // if( this.saveData.saleBeginDate){
          //   this.saveData.saleBeginDate = moment(this.saveData.saleBeginDate).format('YYYY-MM-DD HH:mm:ss');
          // }
          // if( this.saveData.saleEndDate){
          //   this.saveData.saleEndDate = moment(this.saveData.saleEndDate).format('YYYY-MM-DD HH:mm:ss');
          // }
          this.loading = true;
          let res = await editSave(this.saveData);
          if (res.resultCode === 200) {
            this.$emit('save');
            this.$notify.success({ title: '提示信息', message: '保存成功' });
          } else {
            this.loading = false;
          }
        }
      }else {
        this.$refs.formPanel.SUBMIT_FORM();
        if (this.saveData) {
          // this.saveData.ruleType = 58021003;
          let arr3 = [];
          this.$refs.table.$refs.pageTable.list.map(x => {
            arr3.push(x);
          });
          this.saveData.list = arr3;

          let arr4 = [];
          this.$refs.table2.$refs.pageTable.list.map(x => {
            arr4.push(x);
          });
          this.saveData.partList = arr4;
          if(this.saveData.beginDate){
            this.saveData.beginDate = moment(this.saveData.beginDate).format('YYYY-MM-DD HH:mm:ss');
          }
          if(this.saveData.endDate){
            this.saveData.endDate = moment(this.saveData.endDate).format('YYYY-MM-DD HH:mm:ss');
          }
          if(this.saveData.beginEffectDate){
            this.saveData.beginEffectDate = moment(this.saveData.beginEffectDate).format('YYYY-MM-DD HH:mm:ss');
          }
          if(this.saveData.endEffectDate){
            this.saveData.endEffectDate = moment(this.saveData.endEffectDate).format('YYYY-MM-DD HH:mm:ss');
          }
          if(this.saveData.proDate){
            this.saveData.proDate = moment(this.saveData.proDate).format('YYYY-MM-DD HH:mm:ss');
          }
          if( this.saveData.proBeginDate){
            this.saveData.proBeginDate = moment(this.saveData.proBeginDate).format('YYYY-MM-DD HH:mm:ss');
          }
          if( this.saveData.proEndDate){
            this.saveData.proEndDate = moment(this.saveData.proEndDate).format('YYYY-MM-DD HH:mm:ss');
          }
          // if( this.saveData.saleBeginDate){
          //   this.saveData.saleBeginDate = moment(this.saveData.saleBeginDate).format('YYYY-MM-DD HH:mm:ss');
          // }
          // if( this.saveData.saleEndDate){
          //   this.saveData.saleEndDate = moment(this.saveData.saleEndDate).format('YYYY-MM-DD HH:mm:ss');
          // }
          this.loading = true;
          let res = await newSave(this.saveData);
          if (res.resultCode === 200) {
            this.$emit('save');
            this.$notify.success({title: '提示信息', message: '保存成功'});
          } else {
            this.loading = false;
          }
        }
      }
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false, data: this.selectedRows, type: 'close' });
    },
    chooseOrderNo() {
      this.visible = true;
    },
    add() {
      this.visibleAdd = true;
    },
    delsFunSj(data) {
      this.$refs.table.$refs.pageTable.EXECUTE_DELETE([data]);
    },
    //主损件
    zhusunjianClose() {
      this.zhusunjian = false;
    },
    zhusunjianSave(val) {
      let falg = true ;

      this.$refs.table.$refs.pageTable.list.map(x => {
        if(val[0].partCode == x.partCode){
          falg = false;
          this.$notify.error({ title: '提示信息', message: '配件选择重复' });
        }
      });
      if(falg){
        this.$refs.table2.$refs.pageTable.EXECUTE_INSERT(val);
      }
      this.zhusunjian = false;
    },
    chexingclose() {
      this.visible = false;
    },
    chexingsave(obj) {
      this.formList.find(x => x.fieldName == 'modelCode').initialValue = obj[0].modelCode;
      this.modelId = obj[0].modelId;
      this.modelName = obj[0].modelName;
      this.visible = false;
    },
    selectpartCode() {
      this.zhusunjian = true;
    },
    vinsave(obj){
      this.formList.find(x => x.fieldName == 'vin').initialValue = obj[0].vin;
      this.formList.find(x => x.fieldName == 'proDate').initialValue = obj[0].prodDate;
      this.visibleVin = false;
    },
    vinclose(){
      this.visibleVin = false;
    },
    chooseVinNo(){
      this.visibleVin = true;
    },
    deleteFunweixiu(costItem) {
      this.$refs.table2.$refs.pageTable.EXECUTE_DELETE([costItem]);
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '规则编码',
          fieldName: 'ruleCode',
          readonly : true,
          disabled: true, // 置灰
        },
        {
          type: 'INPUT',
          label: '规则描述',
          fieldName: 'ruleInfo',
          rules: [{ required: true, message: '请输入规则编码', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '请输入',
          initialValue: '',
          readonly: true,
          // rules: [{ required: true, message: '请选择VIN码', trigger: 'change' }],
          unitRender: p => {
            return (
              <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.chooseVinNo()} />
              </div>
            );
          }
        },
        {
          type: 'DATE',
          label: '生产日期',
          fieldName: 'proDate',
          disabled:true,
          // rules: [{ required: true, message: '请选择生产日期', trigger: 'change' }],
        },
        // {
        //   type: 'INPUT',
        //   label: '主损件代码',
        //   fieldName: 'partCode',
        //   placeholder: '请输入',
        //   initialValue: '',
        //   rules: [{ required: true, message: '请选择主损件代码', trigger: 'change' }],
        //   readonly : true,
        //   unitRender: p => {
        //     return (
        //       <div>
        //         <multiuse-button icon="el-icon-search" onClick={() => this.selectpartCode()} />
        //       </div>
        //     );
        //   }
        // },
        // {
        //   type: 'INPUT',
        //   label: '主损件名称',
        //   fieldName: 'partName',
        //   readonly : true,
        //   disabled: true, // 置灰
        // },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modelCode',
          placeholder: '请输入',
          initialValue: '',
          readonly : true,
          rules: [{ required: true, message: '请选择车型', trigger: 'change' }],
          unitRender: p => {
            return (
              <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.chooseOrderNo()} />
              </div>
            );
          }
        },
        {
          type: 'RANGE_DATE',
          label: '生产时间',
          fieldName: 'proBeginDate|proEndDate',
          style: { minWidth: '200px' },
          rules: [{ required: true, message: '请选择生产时间', trigger: 'change' }],
          valueFormat: 'yyyy-MM-dd'
        },
        // {
        //   type: 'RANGE_DATE',
        //   label: '销售时间',
        //   fieldName: 'saleBeginDate|saleEndDate',
        //   style: { minWidth: '200px' },
        //   rules: [{ required: true, message: '请选择销售时间', trigger: 'change' }],
        //   valueFormat: 'yyyy-MM-dd'
        // },
        {
          type: 'RANGE_INPUT_NUMBER',
          label: '销售期限',
          fieldName: 'saleBeginTime|saleEndTime',
          style: { minWidth: '200px' },
          rules: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if(!value) {
                  return callback(new Error('请输入销售期限...'));
                }
                const reg = /^[1-9]\d*$/;
                console.log(reg.test(value));
                console.log(value);
                if (reg.test(value[0])&&reg.test(value[1])) {
                  callback();
                }else{
                  callback(new Error('请输入正整数...'));
                }

              },
              trigger: ['blur', 'change'],
            },
          ],
        },
        {
          type: 'RANGE_DATE',
          label: '生效时间',
          fieldName: 'beginEffectDate|endEffectDate',
          style: { minWidth: '200px' },
          rules: [{ required: true, message: '请输入时间', trigger: 'change' }],
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'ruleStatus',
          itemList: [{ text: '禁用', value: 0 },{ text: '启用', value: 1 }],
          rules: [{ required: true, message: '请选择状态', trigger: 'change' }],
        },
        {
          type: 'SELECT',
          label: '是否包含批量活动',
          fieldName: 'isAct',
          itemList: this.createDictList('5500'),
          initialValue: 55001002,
          style: { minWidth: '150px' },
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
        },
        {
          type: 'SELECT',
          label: '是否复发',
          fieldName: 'partId',
          itemList: [{text: '是', value: '0'}, {text: '否', value: '1'}],
          initialValue: '1',
          style: { minWidth: '150px' },
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          disabled : true
        },
        {
          type: 'TEXT_AREA',
          label: '故障描述',
          fieldName: 'remarks',
          placeholder: '备注',
          rows: 2,
          selfCols: 2, // 元素占据几行
        }
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: props => {
            return (
              <div style="text-align:center">
              <multiuse-button type="text" onClick={() => this.delsFunSj(props.row)}>
                删除
              </multiuse-button>
            </div>
          );
          }
        },
        { title: '经销商代码', dataIndex: 'dealerCode', sorter: true },
        { title: '经销商名称', dataIndex: 'dealerName', sorter: true }
      ];
    },
    //table表头和数据源
    creatHeaderPart() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          fixed: 'left',
          width: 80,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          render: (props, h) => {
            return (
              <div style="text-align:center">
                <multiuse-button  size="mini" type="text" onClick={() => this.deleteFunweixiu(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          }
        },
        { title: '配件代码', dataIndex: 'partCode', sorter: true },
        { title: '配件名称', dataIndex: 'partName', sorter: true }
        ];
    }
  }
};
</script>

<style lang="less" scoped></style>
